package com.frame.project.core.aspect;

import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Order(0)
@Component
@Aspect
public class WebLogAspect {
	private  static Logger logger = LogManager.getLogger(WebLogAspect.class);
	
	//定义切入点表达式，只拦截 web包下的 含有后缀Controller名字的类
	@Pointcut("execution(public * com.frame.project..web..*Controller.*(..))")
	public void webLog() {
		// TODO Auto-generated method stub

	}
	
	@Before("webLog()")
	public void doBefore() {
		//接收到请求,记录请求内容
		ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		//记录下请求内容
		logger.info("URL:"+request.getRequestURL().toString());
		logger.info("HTTP_METHOD:"+request.getMethod());
		logger.info("IP:"+request.getRemoteAddr());
		Enumeration<String> enu = request.getParameterNames();
		while (enu.hasMoreElements()) {
			String name = (String) enu.nextElement();
			logger.info("name:{},value:{}",name,request.getParameter(name));
		}
	}
	
	//返回结果
	@AfterReturning(returning="ret",pointcut="webLog()")
	public void doAfterReturning(Object ret) {
		logger.info("RESPONSE:"+ret);
	}
	
}
